<!--
 * @Author: LiZhiWei
 * @Date: 2025-07-14 08:58:30
 * @LastEditors: wjc
 * @LastEditTime: 2025-10-28 14:26:51
 * @Description: 
-->
<template>
  <div class="pt-40px pb-80px relative">
    <Former
      ref="former"
      v-loading="loading"
      :cancel-button="false"
      :data="createFormer.data"
      :fields="createFormer.fields"
      :loading="formLoading"
      :validate="createFormer.validate"
      max-height="auto"
      v-bind="$attrs"
      @on-confirmed="onConfirmed"
    >
      <template v-for="(_, name) in $slots" #[name]="slotData">
        <slot :name="name" v-bind="slotData"></slot>
      </template>
    </Former>
  </div>
</template>

<script setup lang="ts">
  import { useCreator } from '#/hooks/useCreator'

  defineOptions({
    name: 'CreatorEmbed',
  })

  const props = withDefaults(
    defineProps<{
      entity?: string
      message?: string
      requestUrl?: RequestUrl
    }>(),
    {
      entity: '',
      requestUrl: () => ({}),
      message: '提交成功',
    }
  )

  const emits = defineEmits<{
    (e: 'on-stored', res: object): void
  }>()

  const former = ref()

  const {
    loading,
    formLoading,
    createFormer,
    getCreateForm,
    getCreateFormWith,
    handleStore,
    handleStoreWith,
  } = useCreator({
    entity: props.entity,
    mode: 'embed',
    message: props.message,
  })

  const onConfirmed = (form: object) => {
    const onStored = (res: any) => {
      emits('on-stored', res.data)
      former.value?.resetFields()
    }

    if (props.requestUrl?.store) {
      return handleStoreWith(
        {
          store: props.requestUrl.store as string,
          params: { ...props.requestUrl.params, ...form },
        },
        onStored
      )
    }

    return handleStore(form, onStored)
  }

  const loadCreateForm = () => {
    if (props.requestUrl.create) {
      return getCreateFormWith({
        create: props.requestUrl.create as string,
        params: props.requestUrl.params,
      })
    }
    return getCreateForm()
  }

  onMounted(() => {
    loadCreateForm()
  })
</script>
